// hooks/use-auth.ts
import { useEffect } from 'react'
import { useAuthStore } from '@/stores/auth'
import { useRouter, usePathname } from 'next/navigation'

export const useAuth = () => {
  const { token, user, setAuth, clearAuth } = useAuthStore()
  const router = useRouter()
  const pathname = usePathname()

  // 检查是否已认证
  const isAuthenticated = !!token

  // 路由保护
  useEffect(() => {
    // 需要登录的路由
    const protectedRoutes = ['/dashboard', '/profile', '/settings']
    // 不需要登录的路由
    const publicRoutes = ['/login', '/register']

    if (
      !isAuthenticated &&
      protectedRoutes.some((route) => pathname.startsWith(route))
    ) {
      router.push('/login')
    }

    if (isAuthenticated && publicRoutes.includes(pathname)) {
      router.push('/dashboard')
    }
  }, [isAuthenticated, pathname, router])

  return {
    isAuthenticated,
    user,
    setAuth,
    clearAuth,
  }
}
